﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using com.dz.ct.components;
using com.dz.ct.db;
using com.dz.ct.common;
using System.Threading;
using System.Text.RegularExpressions;
using com.dz.ct.components.SmallSite.www.google.com;
using System.Web;
using com.dz.ct.html;

namespace com.dz.ct.business
{
    public class GoogleCollectManager
    {
        /// <summary>
        /// 数据访问对象
        /// </summary>
        private DBManager m_db_mgr = new DBManager();
        /// <summary>
        /// 文件读写
        /// </summary>
        FileManager m_file_mgr = new FileManager();
        /// <summary>
        /// 线程数量
        /// </summary>
        public int ThreadCount { get; set; }
        /// <summary>
        /// 每个线程的收录量
        /// </summary>
        private int m_per_thread_count = 0;
        /// <summary>
        /// 需要收录章节的书籍记录
        /// </summary>
        private int m_total_count = 0;
        /// <summary>
        /// 触发发送消息的事件
        /// </summary>
        public event SendMsgEventHandler SendMsg;

        /// <summary>
        /// google收录数据结合
        /// </summary>
        DataSet m_google_ds = null;
        /// <summary>
        /// 需要收录书籍的SQL
        /// </summary>
        public string BookSQL { get; set; }
        /// <summary>
        /// 盗版站点ID
        /// </summary>
        public int SiteId { get; set; }

        /// <summary>
        /// 接口对象
        /// </summary>
        IBigSiteObject m_obj = null;

        /// <summary>
        /// goog收录对象
        /// </summary>
        SmallSiteObject m_google_mgr = new SmallSiteObject();

        /// <summary>
        /// 接口变量
        /// </summary>
        public string ComName { get; set; }

        #region 消息回送
        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="i_msg"></param>
        private void SendMsg2Client(string i_msg, MsgType i_msg_type)
        {
            SendMsgEventArgs e = new SendMsgEventArgs();
            e.Msg = i_msg;
            e.MsgType = i_msg_type;
            if (SendMsg != null)
            {
                SendMsg(this, e);
            }

        }
        #endregion

        #region google收录逻辑
        /// <summary>
        /// google收录章节
        /// </summary>
        public void StartGoogleSearch()
        {
            if (string.IsNullOrEmpty(BookSQL))
            {
                BookSQL = "select bookCategoryId, bookid,bookName,chapterUrl,lastupdatechaptername from tbbook a where  not exists(select 1 from tbbookcompleted b where a.bookid=b.bookid)";
            }

            try
            {
                m_google_ds = m_db_mgr.QueryData(BookSQL);
                if (m_google_ds != null && m_google_ds.Tables[0].Rows.Count > 0)
                {
                    m_total_count = m_google_ds.Tables[0].Rows.Count;

                    m_per_thread_count = m_total_count / ThreadCount;

                    for (int index = 0; index < ThreadCount; index++)
                    {
                        Thread t_thd = new Thread(ThreadGoogleCollect);

                        t_thd.Start(index);
                    }

                    for (int index = ThreadCount * m_per_thread_count; index < m_total_count; index++)
                    {
                        CollectChapterContent(m_google_ds.Tables[0].Rows[index]);
                    }

                    SendMsg2Client(string.Format("{0}本小说需要收录章节，{1}个线程同时进行，每个线程{2}本书", m_total_count, ThreadCount, m_per_thread_count), MsgType.Total);
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("google收录章节失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 收集小说章节
        /// </summary>
        /// <param name="i_thd_index"></param>
        private void ThreadGoogleCollect(object i_thd_index)
        {
            int t_thd_index = (int)i_thd_index;

            for (int index = t_thd_index * m_per_thread_count; index < (t_thd_index + 1) * m_per_thread_count; index++)
            {
                CollectChapterContent(m_google_ds.Tables[0].Rows[index]);
            }

        }


        /// <summary>
        /// 收录章节内容
        /// </summary>
        /// <param name="i_book_row"></param>
        private void CollectChapterContent(DataRow i_book_row)
        {

            try
            {
                m_obj = ComManager.CreateBigSiteObj(ComName);

                List<BookChapterInfo> t_chapter_list_source = m_obj.CollectChapterList(i_book_row["chapterUrl"].ToString());

                string t_last_update_chapter_name = i_book_row["lastUpdateChapterName"] == null ? "" : i_book_row["lastUpdateChapterName"].ToString();

                int t_chapter_index = 0;

                int t_vip_chapter_count = 0;

                int t_chapter_count = 0;

                string t_chapter_content = string.Empty;

                bool t_is_compared = false;

                if (t_chapter_list_source != null && t_chapter_list_source.Count > 0)
                {
                    SendMsg2Client(string.Format("小说：{2} 从地址：{0} 收集到{1}个章节..", i_book_row["chapterUrl"].ToString(), t_chapter_list_source.Count, i_book_row["bookName"]), MsgType.Total);

                    if (!string.IsNullOrEmpty(t_last_update_chapter_name))
                    {
                        t_chapter_index = t_chapter_list_source.FindIndex(delegate(BookChapterInfo t_chapter_info)
                        {
                            t_is_compared =NetSiteCatchManager.CompareChapterName(t_chapter_info.ChapterName, t_last_update_chapter_name);
                            if (t_is_compared == false)
                            {
                                t_is_compared =NetSiteCatchManager.CompareChapterName(t_last_update_chapter_name, t_chapter_info.ChapterName);
                            }
                            return t_is_compared;
                        });
                    }
                }
                if (t_chapter_index < 0)
                    t_chapter_index = 0;

                long t_book_id = 0;
                long t_chapter_id = 0;
                string t_chapter_url = string.Empty;

                if (!long.TryParse(i_book_row["bookId"].ToString(), out t_book_id))
                    t_book_id = 0;

                BookChapterInfo t_chapter = null;

                List<BookChapterInfo> t_vip_chapter_list = new List<BookChapterInfo>();

                for (int index = t_chapter_index; index < t_chapter_list_source.Count; index++)
                {
                    t_chapter = t_chapter_list_source[index];

                    t_chapter.BookId = t_book_id;
                    t_chapter.SiteId = SiteId;

                    if (t_chapter.IsVip == false)
                    {
                        t_chapter_content = m_obj.CollectChapterContent(t_chapter_list_source[index].Comfrom);
                        
                        if(string.IsNullOrEmpty(t_chapter_content) || t_chapter_content.Length<100)
                            t_chapter_content = m_obj.CollectChapterContent(t_chapter_list_source[index].Comfrom);

                        if (!string.IsNullOrEmpty(t_chapter_content) && t_chapter_content.Length > 100)
                        {

                            //章节入库
                            t_chapter.WordsCount = t_chapter_content.Length;
                         
                            //章节信息保存到数据库
                            t_chapter_id = m_db_mgr.InsertBookChapter(t_chapter, t_chapter.ChapterName);

                            //章节内容保存到磁盘
                            if (t_chapter_id > 0)
                            {
                                m_file_mgr.WriteBookContent(i_book_row["bookCategoryId"].ToString(), t_book_id, t_chapter_id, t_chapter_content);
                                SendMsg2Client(string.Format("从地址：{0} 收集 {1} 章节内容,章节内容字数：{2}", t_chapter.Comfrom, t_chapter.ChapterName, t_chapter_content.Length), MsgType.Detail);
                            }
                        }
                        else
                        {
                            break;
                        }
                        t_chapter_count++;
                    }
                    else
                    {
                        t_vip_chapter_list.Add(t_chapter_list_source[index]);
                      
                    }
                }

                if (t_vip_chapter_list.Count > 0)
                {
                    t_vip_chapter_list = m_google_mgr.CollectBookChapterList(i_book_row["bookName"].ToString(), t_vip_chapter_list);
                    if (t_vip_chapter_list != null && t_vip_chapter_list.Count > 0)
                    {
                        foreach (BookChapterInfo t_vip_chapter in t_vip_chapter_list)
                        {
                            t_vip_chapter.BookId = t_book_id;
                            t_vip_chapter.SiteId = SiteId;
                            //章节信息保存到数据库
                            t_chapter_id = m_db_mgr.InsertBookChapter(t_vip_chapter, t_vip_chapter.ChapterName);

                            //章节内容保存到磁盘
                            if (t_chapter_id > 0)
                            {
                                m_file_mgr.WriteBookContent(i_book_row["bookCategoryId"].ToString(), t_book_id, t_chapter_id, t_vip_chapter.ChapterContent);
                                SendMsg2Client(string.Format("从地址：{0} 收集 {1} VIP章节内容,章节内容字数：{2}", t_vip_chapter.Comfrom, t_vip_chapter.ChapterName, t_vip_chapter.ChapterContent.Length), MsgType.Detail);

                                t_vip_chapter_count++;
                            }
                        }
                    }

                    SendMsg2Client(string.Format("小说：{2} 收集到 {0} 个VIP章节,{1} 个普通章节", t_vip_chapter_count, t_chapter_count, i_book_row["bookName"]), MsgType.Total);
                }

              

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取网站代码失败" + ex.ToString());
            }

        }
        #endregion
    }
}
